/**
 * 工具类
 * created by Ryan
 */
export default class PortraitTool {

    /** 获取数据类型*/
    static getType(obj) {
        //tostring会返回对应不同的标签的构造函数
        let toString = Object.prototype.toString;
        let map = {
            '[object Boolean]': 'boolean',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Function]': 'function',
            '[object Array]': 'array',
            '[object Date]': 'date',
            '[object RegExp]': 'regExp',
            '[object Undefined]': 'undefined',
            '[object Null]': 'null',
            '[object Object]': 'object'
        };
        if (obj instanceof Element) {
            return 'element';
        }
        return map[toString.call(obj)];
    }

    /** 深拷贝*/
    static deepClone(data) {
        let type = this.getType(data);
        let obj;
        if (type === 'array') {
            obj = [];
        } else if (type === 'object') {
            obj = {};
        } else {
            //不再具有下一层次
            return data;
        }
        if (type === 'array') {
            for (let i = 0, len = data.length; i < len; i++) {
                obj.push(this.deepClone(data[i]));
            }
        } else if (type === 'object') {
            for (let key in data) {
                obj[key] = this.deepClone(data[key]);
            }
        }
        return obj;
    }

    // 复制文本
    static copyText(str) {
        return new Promise((resolve, reject) => {
            const el = document.createElement('textarea');
            el.value = str;
            el.setAttribute('readonly', '');
            el.style.position = 'absolute';
            el.style.left = '-9999px';
            el.style.top = '-9999px';
            document.body.appendChild(el);
            const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
            el.select();
            document.execCommand('copy');
            document.body.removeChild(el);
            if (selected) {
                resolve();
                document.getSelection().removeAllRanges();
                document.getSelection().addRange(selected)
            }
        })
    }

    // 最近的自定义时间
    static latestDefineDays(days) {
        // 计算开始时间
        function computeTimeFun(nowTime) {
            const nowDe = new Date(nowTime),
                yearD = nowDe.getFullYear(),
                monD = nowDe.getMonth() + 1,
                dayD = nowDe.getDate();
            return PortraitTool.formatDate(`${yearD}-${monD}-${dayD} 00:00:00`);
        }

        const now = new Date();
        let nowTime = now.getTime();
        nowTime = nowTime - 86400000 * days;// 86400000是一天的毫秒数
        const startTime = computeTimeFun(nowTime);
        const computeTime = computeTimeFun(now.getTime()).replace(/-/g, '/');
        const time = new Date(computeTime).getTime() + 24 * 60 * 60 * 1000 - 1000;
        const endTime = PortraitTool.formatDate(new Date(time));
        return [startTime, endTime]
    }

    // 时间格式化
    static formatDate(v, format) {
        function parseDate(str) {
            if (typeof str == 'string') {
                var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
                if (results && results.length > 3)
                    return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10));
                results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
                if (results && results.length > 6)
                    return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10));
                results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,5}) *$/);
                if (results && results.length > 7)
                    return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10), parseInt(results[7], 10));
            }
            return null;
        }

        if (!format) {
            format = "yyyy-MM-dd hh:mm:ss";
        }
        if (typeof v == 'string') v = parseDate(v);
        if (!(v instanceof Date)) {
            return '';
        }
        // tslint:disable-next-line:prefer-const
        var o = {
            "M+": v.getMonth() + 1, // month
            "d+": v.getDate(), // day
            "h+": v.getHours(), // hour
            "m+": v.getMinutes(), // minute
            "s+": v.getSeconds(), // second
            "q+": Math.floor((v.getMonth() + 3) / 3) // quarter
            // "S" : v.getMilliseconds() //millisecond
        };

        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (v.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        if (/(S+)/.test(format)) {
            format = format.replace(RegExp.$1, ("000" + v.getMilliseconds()).substr(("" + v.getMilliseconds()).length))
        }

        // tslint:disable-next-line:prefer-const
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    // 二进制转xls
    static binaryToXls(data, fileName) {
        let blob = new Blob([data], { type: "application/vnd.ms-excel" }); // 将服务端返回的文件流excel文件
        fileName = fileName + '.xlsx'; // 保存的文件名
        if (window.navigator.msSaveOrOpenBlob) {
            // IE10
            navigator.msSaveBlob(blob, fileName);
        } else {
            let link = document.createElement("a");
            link.style.display = "none";

            link.href = URL.createObjectURL(blob); //创建一个指向该参数对象的URL
            link.download = fileName;
            link.click(); // 触发下载
            URL.revokeObjectURL(link.href); // 释放通过 URL.createObjectURL() 创建的 URL
        }
    }
    //获取最近一个月天数
    static getMonthDay(){ 
        var date = new Date();
        var year = date.getFullYear();
        var day = date.getDate();
        var month = date.getMonth();
        if(day >= 30){ //如果当前为 30日 或者 31日  计算本月天数
            month += 1;
        }else if(month + 1 === 2){//如果当前为 2月
            if((year%4==0&&year%100!=0||year%400==0) && day > 28){ //闰年
                month += 1;
            }else if (!(year%4==0&&year%100!=0||year%400==0) && day >= 28) { // 平年
                month += 1;
            }
        }
        var d = new Date(year, month, 0);
        return d.getDate();
   }

   static toTreeData(data,keys) {
    var pos = {};
    var tree = [];
    var i = 0;
    while (data.length != 0) {
      if (data[i].pid == null || data[i].pid === '' || data[i].pid === '0000000000000000') {
        tree.push({
          id: data[i].id,
          name: data[i].name,
          children: [],
        });
        pos[data[i].id] = [tree.length - 1];
        data.splice(i, 1);
        i--;
      } else {
        var posArr = pos[data[i].pid];
        if (posArr != undefined) {
          var obj = tree[posArr[0]];
          for (var j = 1; j < posArr.length; j++) {
            obj = obj.children[posArr[j]];
          }

          let item = {
            id: data[i].id,
            name: data[i].name,
            children: [],
            pid:data[i].pid
          }
    
          if(keys && keys.length > 0){
            for(let x=0,y=keys.length;x <y;x++){
                // if(item.name === '我的妈呀'){
                //     console.log(data[i])
                //     debugger
                // }
                data[i] && keys[x] && (item[keys[x]] = data[i][keys[x]])
            }
          }
          obj.children.push(item);
          pos[data[i].id] = posArr.concat([obj.children.length - 1]);
          data.splice(i, 1);
          i--;
        }
      }
      i++;
      if (i > data.length - 1) {
        i = 0;
      }
    }
    return tree;
  }

  //获取最近一个月天数
    static sortByPingying(obj) { 
        if(obj.children && obj.children.length > 0){
            console.log(12)

            obj.children = obj.children.sort(function(a,b){
                return a.name.localeCompare(b.name);
            })
            obj.children.forEach((item)=>{
                PortraitTool.sortByPingying(item)
            })
        }
    }
}


